<template>
  <div class="container">
    <n-drawer v-model:show="isDrawer" :width="width">
      <n-drawer-content :title="title" closable>
        <n-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          :label-width="100"
        >
          <n-form-item label="用户名" path="username">
            <n-input placeholder="请输入用户名" v-model:value="formParams.username" />
          </n-form-item>
          <n-form-item label="昵称" path="nickname">
            <n-input placeholder="请输入昵称" v-model:value="formParams.nickname" />
          </n-form-item>
          <n-form-item label="头像" path="avatar">
            <n-upload
              action="https://www.mocky.io/v2/5e4bafc63100007100d8b70f"
              list-type="image-card"
            />
          </n-form-item>
          <n-form-item label="手机号" path="phone">
            <n-input placeholder="请输入手机号" v-model:value="formParams.phone" />
          </n-form-item>
          <n-form-item label="邮箱" path="email">
            <n-input placeholder="请输入邮箱" v-model:value="formParams.email" />
          </n-form-item>
          <n-form-item label="地址" path="address">
            <n-input placeholder="请输入地址" v-model:value="formParams.address" />
          </n-form-item>
          <n-form-item label="类型" path="type">
            <n-select
              v-model:value="formParams.type"
              filterable
              placeholder="选择用户类型"
              :options="typeOptions"
            />
          </n-form-item>
          <n-form-item label="性别" path="sex">
            <n-radio-group v-model:value="formParams.sex" name="sexRadioGroup">
              <n-space>
                <n-radio v-for="sex in sexs" :key="sex.value" :value="sex.value">
                  {{ sex.label }}
                </n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item>
          <n-form-item label="状态" path="state">
            <n-switch v-model:value="formParams.state" default-value />
          </n-form-item>
        </n-form>

        <template #footer>
          <n-space>
            <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
            <n-button @click="handleReset">重置</n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>
<script lang="ts" setup>
  import { PlusOutlined } from '@vicons/antd';
  import { defineProps, reactive, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { addUser } from '@/api/system/user';
  import axios from 'axios';
  const rules = {
    label: {
      required: true,
      message: '请输入标题',
      trigger: 'blur',
    },
    path: {
      required: true,
      message: '请输入路径',
      trigger: 'blur',
    },
  };
  defineExpose({
    openDrawer,
  });

  defineProps({
    title: {
      type: String,
      default: '添加用户',
    },
    width: {
      type: Number,
      default: 450,
    },
  });

  const message = useMessage();
  const formRef: any = ref(null);
  const defaultValueRef = () => ({
    username: '',
    nickname: '',
    phone: '',
    email: '',
    address: '',
    type: 0,
    state: 1,
    sex: 1,
  });
  let isDrawer = ref(false);
  let subLoading = ref(false);

  let formParams = reactive({
    username: '',
    nickname: '',
    phone: '',
    email: '',
    address: '',
    type: 0,
    state: 1,
    sex: 1,
    avatar: '',
  });

  const sexs = [
    {
      value: 1,
      label: '男',
    },
    {
      value: 0,
      label: '女',
    },
  ];
  const typeOptions = [
    {
      label: '管理员',
      value: 1,
    },
    {
      label: '普通用户',
      value: 0,
    },
  ];

  function openDrawer() {
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  const customUpload = ({
    file,
    data,
    headers,
    withCredentials,
    action,
    onFinish,
    onError,
    onProgress,
  }) => {
    const formData = new FormData();
    if (data) {
      Object.keys(data).forEach((key) => {
        formData.append(key, data[key]);
      });
    }
    formData.append(file.name, file.file);
    axios
      .post(action, {
        withCredentials,
        headers,
        body: formData,
        onUploadProgress: ({ percent }) => {
          onProgress({ percent: Math.ceil(percent) });
        },
      })
      .then(({ json }) => {
        message.success(JSON.stringify(json));
        onFinish();
      })
      .catch((error) => {
        message.success(error.message);
        onError();
      });
  };

  const formSubmit = () => {
    formRef.value.validate(async (errors) => {
      if (!errors) {
        console.log(formParams);
        await addUser(formParams);
        message.success('添加成功');
        // handleReset();
        closeDrawer();
      } else {
        message.error('请填写完整信息');
      }
    });
  };

  function handleReset() {
    formRef.value.restoreValidation();
    formParams = Object.assign(formParams, defaultValueRef());
  }
</script>
<style lang="less" scoped></style>
